<?php
class BC_Colorswatch_Model_Attribute_Observer{
    public function bcSaveAttributeData($observer){
        $attribute = $observer->getEvent()->getAttribute();
		if($attribute->getIsGlobal() and $attribute->getFrontendInput()=='select' and $attribute->getIsConfigurable()) : 
        $swatchModel = Mage::getModel('colorswatch/colorswatch');
        $swatchModel->load($attribute->getId(), 'attribute_id');
        $data = array();
        $data['color'] = Mage::app()->getRequest()->getPost()['color'];
        if($swatchModel)
        {
            $originaldata = unserialize($swatchModel->getContent());
            $data['image'] = $originaldata['image'];
        }
        if(isset($_FILES)){
            foreach($_FILES as $key=>$file){
                if($file and file_exists($file['tmp_name']))
                    try {
                        $uploader = new Varien_File_Uploader($key);
                        $uploader->setAllowedExtensions(array('jpg','jpeg','gif','png'));
                        $uploader->setAllowRenameFiles(false);
                        $uploader->setFilesDispersion(false);
                        $path = Mage::getBaseDir('media') . DS .'bc_colorswatch' .DS ;
                        $uploader->save($path, $file['name']);
                        $data['image'][(int)$key] = $file['name'];
                    } catch (Exception $e) {
                    }
            }
        }
        $data = serialize($data);
        $swatchModel->setAttribute_id($attribute->getId())->setContent($data);
        if ($swatchModel->getCreatedTime == NULL || $model->getUpdateTime() == NULL) {
            $swatchModel->setCreatedTime(now())->setUpdateTime(now());
        } else {
            $swatchModel->setUpdateTime(now());
        }
        $swatchModel->save();
		endif;
    }
    public function bcChangeTemplateProductGallery($observer){
        $block = $observer->getEvent()->getBlock()->setTemplate('bc_colorswatch/gallery-bc-colorswatch.phtml');
    }
    public function testAfterSaveProduct($observer){
        $product = $observer->getEvent()->getProduct();
		if(!$product->isConfigurable()) return;
		$postData = Mage::app()->getRequest()->getParams('colorswatch');
		if(!isset($postData['colorswatch'])) return;
		$colorswatchImagesModel = Mage::getModel('colorswatch/images');
        $colorswatchImagesModel -> load($product->getId(), 'product_id');
		if(!$colorswatchImagesModel)
			$colorswatchImagesModel->setProduct_id($product->getId());
        $colorswatchImagesModel -> setContent(serialize($postData['colorswatch']));
		if ($colorswatchImagesModel	-> getCreatedTime == NULL || $model->getUpdateTime() == NULL) {
			$colorswatchImagesModel	-> setCreatedTime(now())
									-> setUpdateTime(now());
		} else {
			$colorswatchImagesModel -> setUpdateTime(now());
		}
		$colorswatchImagesModel->save();
    }
}